package com.atguigu.oss.controller;

import com.aiguigu.commonutils.R;
import com.atguigu.servicebase.exceptionhandler.GuLiException;
import com.atguigu.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;

/**
 * @title: FileController
 * @Author danghailiang
 * @Date: 2022/9/23 18:40
 * @Version 1.0
 */

@RestController
//@CrossOrigin //跨域
@Api(tags = "阿里云文件上传")
@RequestMapping("/api/oss/file")
public class FileController {

    @Resource
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public R upload(
            @ApiParam(value = "文件", required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "模块名称",required = true)
            @RequestParam("module") String module
    ){
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String url = fileService.upload(inputStream, module, originalFilename);
            return R.ok().message("文件上传成功").data("url",url);
        }catch (IOException e){
            throw new GuLiException();
        }
    }

    @ApiOperation("文件删除")
    @DeleteMapping("remove")
    public R remove(
            @ApiParam(value = "文件路径", required = true)
            @RequestParam("url") String url){
        fileService.remove(url);
        return R.ok().message("文件删除成功");
    }

}